import React, {useReducer} from 'react';

function reducer(state, action) {
    switch (action.type) {
        case 'add':
            return state + 1;
        case 'sub':
            return state - 1;
        default:
            throw Error("")
    }
}

function ReducerDemo(props) {

    // reducer，计算过程，和redux中reducer使用方法一致
    const [count, dispatch] = useReducer(reducer, 0);

    return (
        <div>
            <p>{count}</p>
            <button onClick={() => dispatch({type: 'add'})}>+</button>
            <button onClick={() => dispatch({type: 'sub'})}>-</button>
        </div>
    );
}

export default ReducerDemo;
